<template>
  <div class="xpage">
    <!-- 查询表单 -->
    <ele-form-search
      :formConfig="formConfig"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
      ref="eleFormSearch"
    ></ele-form-search>
    <!-- 列表展示 -->
    <ele-table
      ref="xTable"
      :pageSizes="[50, 100, 150]"
      :pageSize="50"
      :pagination="false"
      maxHeight="calc(100vh - 270px)"
      :column="stepsColumn"
      :operateList="operateList"
      :beforeRequest="beforeRequest"
      @handleOperateEvent="handleOperateEvent"
      :apiImmediate="false"
      :getList="getTableData"
      :transFormdata="transFormdata"
      v-loading="loading"
    ></ele-table>
    <!-- 选择型号、物料 -->
    <SelectProd ref="selectProd" @getSelectProd="getSelectProd"></SelectProd>
    <!-- 选择正则判断-->
    <ele-dialog-table
      :title="$t('mesProductProcessSteps.regularDialogTitle')"
      width="800px"
      :visible.sync="regularVisible"
      :formConfig="regularSearchDialog"
      :column="regularColumn"
      @getSelectData="getSelectRegular"
      :getList="mesRegularConfiguration"
      :hasFooter="true"
    ></ele-dialog-table>
  </div>
</template>
<script>
import eleFormSearch from "@/components/ele-form-search/index";
import { searchArrKey } from "@/mixins/searchArrKey";
import {
  formConfig,
  tableSteps,
  regularSearchDialog,
  regularColumn,
} from "../config.js";
import {
  getTableData,
  baseUnitConversion,
  mesRegularConfiguration,
  saveTable,
  exportUrl,
  sort,
} from "@/api/process/mesProductProcessSteps";
import { getDict } from "@/api/common";
import SelectProd from "./selectProd";
import { exportExcel } from "@/utils/judge";
import url from "@/axios/url";
const { minioUrl } = url();
export default {
  name: "tableSteps",
  mixins: [searchArrKey, tableSteps],
  components: { eleFormSearch, SelectProd },

  data() {
    return {
      formConfig,
      getTableData,
      currentData: {},
      typeList: [], //类型
      unitList: [], //单位
      sequenceList: [], //顺序类型
      tableTndex: 0,
      regularVisible: false,
      mesRegularConfiguration,
      regularSearchDialog,
      regularColumn,
      loading: false,
      initLength: 0, //表格数据长度
    };
  },
  created() {
    this.getType();
    this.baseUnitConversion();
    this.getSequenceType();
  },
  methods: {
    init(currentData, oldData) {
      //判断是否修改、新增过、删除过，有则提示保存
      if (this.isExistOperate()) {
        this.$confirm(
          this.$t("mesProductProcessSteps.checkIsSaveNote"),
          $i18n.t("common.tip"),
          {
            confirmButtonText: $i18n.t("common.ok"),
            cancelButtonText: $i18n.t("common.cancel"),
            type: "warning",
            showClose: false,
          }
        )
          .then(() => {
            this.currentData = currentData;
            if (oldData) {
              try {
                this.saveTable(oldData.at(-2));
              } catch (error) {
                console.error(error);
              }
            } else {
              this.saveTable();
            }
          })
          .catch(() => {
            this.refresh(false);
          });
      } else {
        this.currentData = currentData;
        if (currentData.levelType != "gx") {
          this.$refs.xTable.data = [];
          this.initLength = 0;
          return;
        }
        this.refresh();
      }
    },
    isExistOperate() {
      const data = this.$refs.xTable.data;
      const exist = data.some((val) => val.isAdd || val.isEdit);
      return this.initLength != data.length || exist;
    },
    handleSearch() {
      this.refresh();
    },
    handleReset() {
      this.refresh();
    },
    getSearchParams() {
      let formData = this.$refs.eleFormSearch.formData || {};
      formData = this.getArrtoMap(formData);
      return formData;
    },
    beforeRequest(data) {
      let formData = this.$refs.eleFormSearch.formData || {};
      formData = this.getArrtoMap(formData);
      const {
        seriesCode,
        prodCode,
        technologyCode,
        versionNumber,
        processCode,
        levelType,
      } = this.currentData;

      let params =
        levelType == "xl"
          ? {
              ...data,
              ...formData,
              seriesCode,
            }
          : {
              ...data,
              ...formData,
              seriesCode,
              prodCode,
              technologyCode,
              versionNumber,
              processCode,
            };
      delete params.pageNum;
      delete params.pageSize;

      return params;
    },
    refresh(isReset = true) {
      this.$nextTick(() => {
        this.$refs.xTable.getTableData(isReset);
      });
    },
    //表格顶部操作事件
    handleOperateEvent(data) {
      const { handleName } = data;
      const fnc = {
        add: () => {
          const {
            seriesCode,
            seriesName,
            prodCode,
            prodName,
            technologyCode,
            technologyName,
            versionNumber,
            processName,
            processCode,
          } = this.currentData;
          let arr = JSON.parse(JSON.stringify(this.$refs.xTable.data || []));

          let parallelNumber = 0;
          if (!arr.length) {
          } else {
            parallelNumber = arr
              .sort((a, b) => a.parallelNumber - b.parallelNumber)
              .at(-1).parallelNumber;
          }

          const row = {
            isAdd: true,
            seriesCode,
            seriesName,
            prodCode,
            prodName,
            technologyCode,
            technologyName,
            versionNumber,
            processName,
            processCode,
            enableOrNot: "1", //状态
            isMandatory: "0",
            isCopy: "0",
            classify: "",
            isRepeat: "0",
            unitCode: "",
            step: "",
            warningMessage: "",
            // isEdit:false,
            parallelNumber: parallelNumber + 1, //当前列表最大值+1
            selectMaterialOrNot: "0", //是否选择物料
          };
          this.addTableData(row);
        },
        save: this.saveTable,
        export: () => {
          const {
            seriesCode,
            prodCode,
            technologyCode,
            versionNumber,
            processCode,
            levelType,
          } = this.currentData;
          let data =
            levelType == "xl"
              ? { seriesCode }
              : {
                  seriesCode,
                  prodCode,
                  technologyCode,
                  versionNumber,
                  processCode,
                };

          exportExcel(exportUrl, { ...data, ...this.getSearchParams() });
        },
        preview: () => {
          let data = this.$refs.xTable.data;
          if (data.length) {
            sort(data).then((res) => {
              // this.$refs.xTable.data=[];
              this.$nextTick(() => {
                //res.data.result
                this.$refs.xTable.data = res.data.result.map((ite) => {
                  return {
                    classify: "",
                    isRepeat: "0",
                    unitCode: "",
                    step: "",
                    isEdit: false,
                    enableOrNot: "1", //状态
                    isMandatory: "0",
                    isCopy: "0",
                    selectMaterialOrNot: "0", //是否选择物料
                    warningMessage: "",
                    ...ite,
                  };
                });
              });
            });
          } else {
            this.$message.warning(this.$t("mesProductProcessSteps.mes1"));
          }
        },
        download: () => {
          window.open(`${minioUrl}/mes-template/产品工艺步骤模板.xls`, "_self");
        },
      };
      fnc[handleName] && fnc[handleName]();
    },
    //表格行操作事件
    rowOperate({ handleName, name, row, $index }) {
      const fnc = {
        edit: () => {
          this.$set(this.$refs.xTable.data[$index], "isEdit", true);
        },
        delete: () => {
          this.$confirm(
            this.$t("mesProductProcessSteps.removeItem"),
            this.$t("common.tip"),
            {
              confirmButtonText: $i18n.t("common.ok"),
              cancelButtonText: $i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.$refs.xTable.data.splice($index, 1);
          });
        },
        copy: () => {
          let newRow = JSON.parse(JSON.stringify(row));
          delete newRow.id;
          newRow.isAdd = true;
          this.$refs.xTable.data.splice($index + 1, 0, newRow);
          console.log("复制", newRow);
        },
        up: () => {
          if ($index == 0) return;
          let data = this.$refs.xTable.data;
          this.$refs.xTable.data = this.swapArray(data, $index, $index - 1);
        },
        down: () => {
          let data = this.$refs.xTable.data;
          if ($index == data.length - 1) return;

          this.$refs.xTable.data = this.swapArray(data, $index, $index + 1);
        },
      };
      fnc[handleName]();
    },
    //交换位置
    swapArray(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    //判断是否是工序
    isgx() {
      return this.currentData.levelType == "gx";
    },
    //请求类型
    getType() {
      getDict("step_type").then((res) => {
        let data = res.data.result || [];
        data.forEach((val) => (val.label = val.description));
        this.typeList = data;
      });
    },
    //获取计量单位
    baseUnitConversion() {
      baseUnitConversion().then((res) => {
        let data = res.data.result || [];
        data.forEach((val) => {
          val.label = val.name;
          val.value = val.code;
        });
        this.unitList = data;
      });
    },
    getSequenceType() {
      getDict("step_sequence_type").then((res) => {
        let data = res.data.result || [];
        data.forEach((val) => (val.label = val.description));
        this.sequenceList = data;
      });
    },

    //判断弹物料框还是扫码框
    handleDialog(scope, model) {
      this.tableTndex = scope.$index;
      if (scope.row.classify == "7") {
        const { processCode } = scope.row;
        this.$refs.selectProd.init({ processCode, isNewApi: true });
      } else {
        this.regularVisible = true;
      }
    },
    //生成输入框
    getInputDom(h, scope, model) {
      return (
        <div>
          {this.isAddOrEdit(scope.row) ? (
            this.getInputNew(h, scope, model)
          ) : (
            <span>{scope.row[model]}</span>
          )}
        </div>
      );
    },
    //生成下拉
    getSelectDOm(h, scope, model, list = []) {
      let itemType = list.find((val) => val.value == scope.row[model]);
      //  console.log(model,scope.row,this.isAddOrEdit(scope.row))
      return (
        <div>
          {this.isAddOrEdit(scope.row) ? (
            this.getSelect(h, scope, model, list)
          ) : (
            <span>{itemType?.label ?? null}</span>
          )}
        </div>
      );
    },
    getSearchInput(h, scope, model) {
      return (
        <el-input
          v-model={scope.row[model]}
          placeholder={$i18n.t("common.select")}
          readonly
        >
          <i
            slot="suffix"
            onClick={() => this.handleDialog(scope, model)}
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
      );
    },
    getInput(h, scope, model) {
      return (
        <el-input
          v-model={scope.row[model]}
          placeholder={$i18n.t("common.input")}
        ></el-input>
      );
    },
    getInputNew(h, scope, model) {
      return (
        <el-input
          v-model={scope.row[model]}
          placeholder={
            model == "referenceValue" || model == "correctOptions"
              ? $i18n.t("mesProductProcessSteps.submitErrorTip8")
              : $i18n.t("common.input")
          }
        ></el-input>
      );
    },
    getInputNumber(h, scope, model) {
      return (
        <el-input-number
          v-model={scope.row[model]}
          placeholder=""
        ></el-input-number>
      );
    },
    getInputNumberNew(h, scope, model) {
      return (
        <el-input-number
          min={0}
          v-model={scope.row[model]}
          placeholder=""
        ></el-input-number>
      );
    },
    getSelect(h, scope, model, list = []) {
      return (
        <el-select
          filterable={true}
          v-model={scope.row[model]}
          placeholder={$i18n.t("common.select")}
          onChange={() => this.handleSelect(scope, model)}
        >
          {list.map((item, index) => {
            return (
              <el-option
                key={`${item.value}-${index}`}
                label={item.label}
                value={item.value}
              ></el-option>
            );
          })}
        </el-select>
      );
    },
    handleSelect(scope, model) {
      let row = scope.row;
      if (model == "classify") {
        const item = {
          ...scope.row,
          parameterMaterial: null,
          referenceValue: undefined,
          upperLimitValue: undefined,
          lowerLimitingValue: undefined,
          unitCode: null,
          selectMaterialOrNot: row.classify == 7 ? "1" : "0",
          unit: null,
        };
        try {
          //选择计数的时候特殊操作,默认单位赋值"个"  by bing
          if (row.classify == "2") {
            let obj = this.unitList.find(
              (ite) => ite.label == $i18n.t("mesProductProcessSteps.several")
            );
            // this.$set(item, "unitCode", obj.value);
            item.unitCode = obj.value;
            row.unitCode = obj.value;
          }
          if (row.classify == "13") {
            let obj = this.unitList.find(
              (ite) => ite.label == $i18n.t("mesProductProcessSteps.seconds")
            );
            //    this.$set(item, "unitCode", obj.value);
            item.unitCode = obj.value;
            row.unitCode = obj.value;
          }
        } catch (error) {
          console.error($i18n.t("mesProductProcessSteps.missingParameter"));
        }
        this.$set(this.$refs.xTable.data, scope.$index, item);

        if (row.classify == "2") {
          // this.$set(this.$refs.xTable.data, scope.$index, item);
        }
      }

      if (model == "unitCode" || ["2", "13"].includes(row.classify)) {
        const val = this.unitList.find((ite) => ite.value == row.unitCode);
        this.$set(this.$refs.xTable.data[scope.$index], "unit", val.label);
      }

      if (model == "orderType") {
        const item = {
          ...scope.row,
          parallelNumber: undefined,
        };
        this.$set(this.$refs.xTable.data, scope.$index, item);
      }
    },
    getSelectProd([data]) {
      const parameterMaterial = data.goodsCode;
      this.$set(
        this.$refs.xTable.data[this.tableTndex],
        "parameterMaterial",
        parameterMaterial
      );
    },
    getSelectRegular([data]) {
      const regularContent = data.regularContent;
      this.$set(
        this.$refs.xTable.data[this.tableTndex],
        "parameterMaterial",
        regularContent
      );
    },
    //是否是添加或者编辑状态
    isAddOrEdit({ isAdd, isEdit }) {
      return isAdd || isEdit;
    },
    //添加行数据
    addTableData(row = {}) {
      this.$refs.xTable.data.push(row);
      this.$nextTick(() => {
        let dom = document.querySelector(".el-table__body-wrapper");
        dom.scrollTo(0, dom.scrollHeight);
      });
    },
    //转化表格数据
    transFormdata(data) {
      let { records = [], total = 0 } = data.data.result;
      this.initLength = records.length;
      records.forEach((val) => {
        val.isAdd = false;
        val.isEdit = false;
      });
      return Promise.resolve({
        records: records,
        total: total,
      });
    },
    //保存
    saveTable(id) {
      let data = this.$refs.xTable.data || [];
      if (!this.checkData(data)) return;
      for (let i = 0; i < data.length; i++) {
        data[i].serialNumber = i + 1;
      }
      const params = {
        detailList: data,
        parentId: id || this.currentData.id,
      };
      this.loading = true;
      saveTable(params)
        .then((res) => {
          this.$message.success(this.$t("common.saveSuccess"));
          this.refresh(false);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    checkData(data) {
      console.log(data);
      //工步、类型、顺序类型必填 step,classify,orderType
      // 类型为计量、计数、计时   参考值、上下限必填 ['1','2','3']
      // 类型为投料和扫描时候：    投料批次号必填 ['7',"8"]
      const empty = [undefined, null, ""];
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if (!item.step || !item.classify) {
          this.$message.error(
            this.$t("mesProductProcessSteps.submitErrorTip", { index: i + 1 })
          );
          return false;
        }

        if (
          ["12"].includes(item.classify) &&
          (empty.includes(item.referenceValue) ||
            empty.includes(item.upperLimitValue) ||
            empty.includes(item.lowerLimitingValue))
        ) {
          this.$message.error(
            this.$t("mesProductProcessSteps.submitErrorTip2", { index: i + 1 })
          );
          return false;
        }
        // console.log(2222, item);
        if (
          ["1", "2", "3", "13"].includes(item.classify) &&
          (empty.includes(item.referenceValue) ||
            empty.includes(item.upperLimitValue) ||
            empty.includes(item.lowerLimitingValue) ||
            empty.includes(item.unit))
        ) {
          this.$message.error(
            this.$t("mesProductProcessSteps.submitErrorTip5", { index: i + 1 })
          );
          return false;
        }
        if (
          ["7"].includes(item.classify) &&
          (empty.includes(item.upperLimitValue) ||
            empty.includes(item.lowerLimitingValue) ||
            empty.includes(item.unit))
        ) {
          this.$message.error(
            this.$t("mesProductProcessSteps.submitErrorTip7", { index: i + 1 })
          );
          return false;
        }
        if (["7", "8"].includes(item.classify) && !item.parameterMaterial) {
          this.$message.error(
            this.$t("mesProductProcessSteps.submitErrorTip3", { index: i + 1 })
          );
          return false;
        }
        // if (["1"].includes(item.orderType) && !item.parallelNumber) {
        //   this.$message.error(
        //     this.$t("mesProductProcessSteps.submitErrorTip4", { index: i + 1 })
        //   );
        //   return false;
        // }
        if (
          ["9", "10"].includes(item.classify) &&
          (empty.includes(item.referenceValue) ||
            empty.includes(item.correctOptions))
        ) {
          this.$message.error(
            this.$t("mesProductProcessSteps.submitErrorTip6", { index: i + 1 })
          );
          return false;
        }
      }
      return true;
    },
  },
};
</script>
<style lang="scss" scoped></style>
